
#include "RtBase.h"
#include "RtChannelHttpServerAcceptor.h"
#include "RtChannelHttpServer.h"
#include "RtHttpUrl.h"

CRtChannelHttpServerAcceptor::
CRtChannelHttpServerAcceptor(CRtChannelManager::CFlag aFlag)
	: m_pSink(NULL)
	, m_FlagAcceptor(aFlag)
{
}

CRtChannelHttpServerAcceptor::~CRtChannelHttpServerAcceptor()
{
}

DWORD CRtChannelHttpServerAcceptor::AddReference()
{
	return CRtReferenceControlSingleThread::AddReference();
}

DWORD CRtChannelHttpServerAcceptor::ReleaseReference()
{
	return CRtReferenceControlSingleThread::ReleaseReference();
}

RtResult CRtChannelHttpServerAcceptor::
StartListen(IRtChannelServerSink *aSink, const CRtInetAddr &aAddrListen)
{
	RtResult rv;
	RT_ASSERTE(!m_pAcceptorTcp);

	RT_ASSERTE_RETURN(aSink, RT_ERROR_INVALID_ARG);
	RT_ASSERTE(!m_pSink);
	m_pSink = aSink;

	CRtConnectionManager::CType typeConnector = CRtConnectionManager::CTYPE_TCP;
	if (RT_BIT_ENABLED(m_FlagAcceptor, CRtChannelManager::CFLAG_SEND_NO_PARTIAL_DATA))
		RT_SET_BITS(typeConnector, CRtConnectionManager::CTYPE_SEND_NO_PARTIAL_DATA);
	rv = CRtConnectionManager::Instance()->CreateConnectionServer(
		typeConnector,
		m_pAcceptorTcp.ParaOut());
	if (RT_FAILED(rv))
		goto fail;

	rv = m_pAcceptorTcp->StartListen(this, aAddrListen);
	if (RT_FAILED(rv))
		goto fail;

	return RT_OK;

fail:
	RT_ASSERTE(RT_FAILED(rv));
	StopListen(rv);
	return rv;
}

RtResult CRtChannelHttpServerAcceptor::
StopListen(RtResult aReason)
{
	RtResult rv = RT_OK;
	if (m_pAcceptorTcp) {
		rv = m_pAcceptorTcp->StopListen(aReason);
		m_pAcceptorTcp = NULL;
	}
	m_pSink = NULL;
	return rv;
}

void CRtChannelHttpServerAcceptor::
OnConnectIndication(RtResult aReason, IRtTransport *aTrpt, 
					IRtAcceptorConnectorId *aRequestId)
{
	RT_ASSERTE(RT_SUCCEEDED(aReason));
	RT_ASSERTE(aTrpt);
	RT_ASSERTE(aRequestId == m_pAcceptorTcp.Get());

	CRtAutoPtr<CRtChannelHttpServer> pChannelHttp 
		= new CRtChannelHttpServer(aTrpt);
	if (!pChannelHttp)
		return;

	RT_ASSERTE(m_pSink);
	if (m_pSink)
		m_pSink->OnServerCreation(pChannelHttp.ParaIn());
}
